package com.amap.flutter.map.location;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.flutter.map.R;
import com.amap.flutter.map.utils.ConvertUtil;
import com.amap.flutter.map.utils.Utils;

import java.util.Map;

import io.flutter.plugin.common.EventChannel;

public class AMapLocationClientImpl implements AMapLocationListener {
    private Context mContext;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();
    private AMapLocationClient locationClient = null;
    private EventChannel.EventSink mEventSink;

    private String mPluginKey;

    public AMapLocationClientImpl(Context context, String pluginKey, EventChannel.EventSink eventSink) {
        mContext = context;
        mPluginKey = pluginKey;
        mEventSink = eventSink;
        try {
            if (null == locationClient) {
                locationClient = new AMapLocationClient(context);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始定位
     */
    public void startLocation(Map option) {
//        Log.d("定位", "开始定位 " + option);
        try {
            if (null == locationClient) {
                locationClient = new AMapLocationClient(mContext);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != locationOption) {
//            Log.d("定位", "设置option 及回调 " + locationOption);
            locationClient.setLocationOption(locationOption);
            locationClient.setLocationListener(this);
            boolean backgroundMode = false;
            if (option.containsKey("background")) {
                backgroundMode = (boolean) option.get("background");
            }
//            Log.d("定位", "backgroundMode " + backgroundMode);
            if (backgroundMode) {
                int notificationId = (int) option.get("notificationId");
                locationClient.enableBackgroundLocation(notificationId, buildNotification(option));
            } else {
                locationClient.disableBackgroundLocation(true);
            }
//            Log.d("定位", "开始定位 startLocation");
            locationClient.startLocation();
        }
    }

    private Notification buildNotification(Map option) {
        Notification.Builder builder;// = new Notification.Builder(mContext);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            String channelId = (String) option.get("channelId");
            String channelName = (String) option.get("channelName");
            int importance = option.get("importance") != null ? ((int) option.get("importance")) : NotificationManager.IMPORTANCE_DEFAULT;
            if (importance < NotificationManager.IMPORTANCE_MIN || importance > NotificationManager.IMPORTANCE_HIGH) {
                importance = NotificationManager.IMPORTANCE_DEFAULT;
            }
            NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
            channel.setDescription((String) option.get("description"));
            channel.setLockscreenVisibility((Integer) option.get("lockscreenVisibility"));
            channel.enableLights((Boolean) option.get("enableLights")); //是否在桌面icon右上角展示小圆点
            if (option.containsKey("lightColor") && option.get("lightColor") != null) {
                int lightColor = ConvertUtil.toInt(option.get("lightColor"));
                channel.setLightColor(lightColor);
            }
            channel.setShowBadge((Boolean) option.get("showBadge")); //是否在久按桌面图标时显示此渠道的通知
            notificationManager.createNotificationChannel(channel);
            builder = new Notification.Builder(mContext, channelId);
        } else {
            builder = new Notification.Builder(mContext);
        }

        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle((String) option.get("title"))
                .setContentText((String) option.get("content"))
                .setWhen(System.currentTimeMillis());

        return builder.build();
    }

    /**
     * 停止定位
     */
    public void stopLocation() {
        if (null != locationClient) {
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
        }
    }

    public void destroy() {
        if (null != locationClient) {
            locationClient.unRegisterLocationListener(this);
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
        }
    }

    /**
     * 定位回调
     *
     * @param location
     */
    @Override
    public void onLocationChanged(AMapLocation location) {
//        Log.d("定位", "mEventSink " + mEventSink + " 位置改变 " + location);
        if (null == mEventSink) {
            return;
        }
//        arguments.put("location", ConvertUtil.location2Map(location));
//        Map<String, Object> result = (Map<String, Object>) ConvertUtil.location2Map(location);
        Map<String, Object> result = Utils.buildLocationResultMap(location);
        result.put("pluginKey", mPluginKey);
        mEventSink.success(result);
    }


    /**
     * 设置定位参数
     *
     * @param optionMap
     */
    public void setLocationOption(Map optionMap) {
        if (null == locationOption) {
            locationOption = new AMapLocationClientOption();
        }

        if (optionMap.containsKey("locationInterval")) {
            locationOption.setInterval(((Integer) optionMap.get("locationInterval")).longValue());
        }

        if (optionMap.containsKey("needAddress")) {
            locationOption.setNeedAddress((boolean) optionMap.get("needAddress"));
        }

        if (optionMap.containsKey("locationMode")) {
            try {
                locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.values()[(int) optionMap.get("locationMode")]);
            } catch (Throwable e) {
            }
        }

        if (optionMap.containsKey("geoLanguage")) {
            locationOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.values()[(int) optionMap.get("geoLanguage")]);
        }

        if (optionMap.containsKey("onceLocation")) {
            locationOption.setOnceLocation((boolean) optionMap.get("onceLocation"));
        }

        if (null != locationClient) {
            locationClient.setLocationOption(locationOption);
        }
    }
}
